package com.zhiyou.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhiyou.bean.*;
import com.zhiyou.service.ProductService;

import com.zhiyou.service.TypeService;
import com.zhiyou.util.Msg;
import org.springframework.stereotype.Controller;


import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.zhiyou.service.RepayService;
import com.zhiyou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.UUID;

import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ProductService productService;

    @Autowired
    UserService userService;

    @Autowired
    RepayService repayService;

    @Autowired
    TypeService typeService;


     @RequestMapping("/getAllProduct")
     public String getAllProduct(@RequestParam(value ="pageNo", defaultValue = "1")Integer pageNo,HttpServletRequest request){
      PageHelper.startPage(pageNo,8);
      List<Product> products=productService.getAllProduct();
       PageInfo page =new PageInfo(products,5);
    request.getSession().setAttribute("products", products);
    request.getSession().setAttribute("pageInfo", page);
       return "redirect:/gyzc-list.jsp";
    }

     //下拉框状态查询  进行分页展示
      @RequestMapping("/getProductsByStatus")
      public  String getProductsByStatus(String value,@RequestParam(value ="pageNo", defaultValue = "1")Integer pageNo,HttpServletRequest request) {
          System.out.println("value="+value);
          PageHelper.startPage(pageNo,8);
              Integer status=Integer.parseInt(value);
              List<Product> products=productService.getProductsByStatus(status);
              PageInfo page =new PageInfo(products,5);
              request.getSession().setAttribute("products",products);
              request.getSession().setAttribute("pageInfo", page);

          return "redirect:/gyzc-list.jsp";
      }

    // 下拉框排序查询  按升序排序进行分页展示
    @RequestMapping("/getProductsByOrder")
    public String getProductsByOrder(String value, @RequestParam(value ="pageNo", defaultValue = "1")Integer pageNo, HttpServletRequest request) {
        PageHelper.startPage(pageNo,8);
        //金额排序
        //按筹款人数查询
        //按日期排序查询
            List<Product> products=productService.getProductsByOrder(value);
            PageInfo page =new PageInfo(products,5);
            request.getSession().setAttribute("products", products);
            request.getSession().setAttribute("pageInfo",page);
        return "redirect:/gyzc-list.jsp";
    }

    //根据公益id 查询product 教育助学--9
    @RequestMapping("/getProductByTypeIdJY")
    public  String getProductByTypeIdJY( String id,@RequestParam(value ="pageNo", defaultValue = "1")Integer pageNo, HttpServletRequest request){
        PageHelper.startPage(pageNo,8);
        List<Product> products=productService.getProductByTypeIdJY(9);
        PageInfo page =new PageInfo(products,5);
        request.getSession().setAttribute("products", products);
        request.getSession().setAttribute("pageInfo",page);
        return "redirect:/gyzc-list.jsp";
    }

    //根据公益id 查询product 爱心环保--6
    @RequestMapping("/getProductByTypeIdAX")
    public  String getProductByTypeIdAX( String id,@RequestParam(value ="pageNo", defaultValue = "1")Integer pageNo, HttpServletRequest request){
        PageHelper.startPage(pageNo,8);
        List<Product> products=productService.getProductByTypeIdAX(6);
        PageInfo page =new PageInfo(products,5);
        request.getSession().setAttribute("products", products);
        request.getSession().setAttribute("pageInfo",page);
        return "redirect:/gyzc-list.jsp";
    }

    // 根据公益id 查询product 扶贫助困---7
    @RequestMapping("/getProductByTypeIdFP")
    public  String getProductByTypeIdFP( String id,@RequestParam(value ="pageNo", defaultValue = "1")Integer pageNo, HttpServletRequest request){
        PageHelper.startPage(pageNo,8);
        List<Product> products=productService.getProductByTypeIdFP(7);
        PageInfo page =new PageInfo(products,5);
        request.getSession().setAttribute("products", products);
        request.getSession().setAttribute("pageInfo",page);
        return "redirect:/gyzc-list.jsp";
    }
    // 根据公益id 查询product 公益创业--8
    @RequestMapping("/getProductByTypeIdCY")
    public  String ggetProductByTypeIdCY( String id,@RequestParam(value ="pageNo", defaultValue = "1")Integer pageNo, HttpServletRequest request){
        PageHelper.startPage(pageNo,8);
        List<Product> products=productService.getProductByTypeIdCY(8);
        PageInfo page =new PageInfo(products,5);
        request.getSession().setAttribute("products", products);
        request.getSession().setAttribute("pageInfo",page);
        return "redirect:/gyzc-list.jsp";
    }

    //根据公益id 查询product 公益活动--1
    @RequestMapping("/getProductByTypeIdHD")
    public  String getProductByTypeIdHD( String id,@RequestParam(value ="pageNo", defaultValue = "1")Integer pageNo, HttpServletRequest request){
        PageHelper.startPage(pageNo,8);
        List<Product> products=productService.getProductByTypeIdHD(1);
        PageInfo page =new PageInfo(products,5);
        request.getSession().setAttribute("products", products);
        request.getSession().setAttribute("pageInfo",page);
        return "redirect:/gyzc-list.jsp";
    }

    //查询全部成功案例 这是标题 ly-list div框内展示五条数据
    //根据状态 3成功案例获取信息 进行ly-list展示 三个   页面不是按这个查找的
     @RequestMapping("/getProductsBySuccessStatus")
      public  String getProductsBySuccessStatus(HttpServletRequest request,@RequestParam(value ="pageNo", defaultValue = "1")Integer pageNo ){
         PageHelper.startPage(pageNo,5);
      List<Product> productslist=productService.getProductsBySuccessStatus(3);
         productslist.stream().forEach(product -> {
          System.out.println(product);
      });
         PageInfo page =new PageInfo(productslist,5);
      request.getSession().setAttribute("productslist",productslist);
       return "redirect:/ly-list.jsp";
      }

    @PostMapping("/upload")
    @ResponseBody
    public String uploadImg(MultipartFile file) {

        return "success";
    }

    @RequestMapping("/test")
    public String test(Product product) {
        System.out.println(product);

        return "success";
    }


    @RequestMapping("/add")
    public String addProduct(User user, Product product, Repay repay, MultipartFile file, HttpSession session) {
        System.out.println(user);
        String src = resolvePic(file, session);
        product.setImageUrl(src);
        product.setUserId(user.getId());
        int i = productService.insertOne(product);
        if (i < 1) {
            return "fail";
        }
        Integer pid = productService.getProductId(product);
        repay.setProductId(pid);
        int j = repayService.insertOne(repay);
        return "redirect:/new_product.jsp";
    }

    private String resolvePic(MultipartFile file, HttpSession session) {
        try {
            String path = session.getServletContext().getRealPath("images");
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + suffix;
            File target = new File(path, newFileName);
            if (!target.getParentFile().exists()) {
                // 新建文件夹
                if (!target.getParentFile().mkdirs()) {
                    System.out.println("【目录为空】新建文件夹失败！");
                    return null;
                }
            }
            file.transferTo(target);
            return "images/" + newFileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //根据id查询
    @RequestMapping("/getProductById")
    public String getProductById(Integer productId, HttpSession session) {

        System.out.println("controller=======");
        Product product = productService.getProductById(productId);

        System.out.println("product = " + product);

        Integer status = product.getStatus();


        Date endTime = product.getEndTime();


        //获取项目当前的状态
        System.out.println("status = " + status);
        if (status == 0) {
            session.setAttribute("statusColor", "white");
            session.setAttribute("status", "制作中");
        } else if (status == 1) {
            session.setAttribute("statusColor", "#FAB928");
            session.setAttribute("status", "预热中");
        } else if (status == 2) {
            session.setAttribute("statusColor","red");
            session.setAttribute("status","筹备中");
        } else if (status == 3) {
            session.setAttribute("statusColor","green");
            session.setAttribute("status","项目成功");
        }

        if (endTime == null) {
            session.setAttribute("date", "暂时未定");
            session.setAttribute("product", product);

            return "product-detail";
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(endTime);
        session.setAttribute("date", format);


        session.setAttribute("product", product);
        return "product-detail";
    }


    @RequestMapping("/Test")
    public String TestController() {
        System.out.println("controller=======");
        return "s";
    }

    @RequestMapping("/getByUserId")
    public String getProductByUserId(@RequestParam(value = "page", defaultValue = "1") int page, HttpSession session) {
        User user = (User) session.getAttribute("user");
        PageHelper.startPage(page, 10);
        List<Product> list = productService.getProductByUserId(user.getId());
        for (Product p : list) {
            Type type = typeService.getTypeById(p.getTypeId());
            p.setProductType(type);
        }
        PageInfo<Product> pageInfo = new PageInfo<>(list, 5);
        session.setAttribute("pageInfo", pageInfo);
        return "redirect:/user.jsp";
    }

    @RequestMapping("/addComment")
    public String addComment(String comment,HttpSession session){
        System.out.println("controller=======");

        User user = new User();
        user.setId(31);

        if (user==null){
            return "login";
        }


        Product product = (Product) session.getAttribute("product");

        System.out.println("product = " + product);

        //获取当前时间
        Date date = new Date();
        System.out.println("date = " + date);


        Comment comment1 = new Comment();

        comment1.setUserId(user.getId());
        comment1.setProductId(product.getId());
        comment1.setCreateTime(date);
        comment1.setContent(comment);

        int i  = productService.addComment(comment1);

        System.out.println("i = " + i);

        return "product-detail";
    }

    @ResponseBody
    @RequestMapping("/getAllComment")
    public List<Comment> getAllComment(@RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo ,HttpSession session){

        Product product = (Product) session.getAttribute("product");

        System.out.println("product = " + product);

        Integer id = product.getId();


        PageHelper.startPage(pageNo,6);

        List<Comment>  list = productService.getAllCommentById(id);

        list.forEach(System.out::println);


        for (int i = 0; i < list.size(); i++) {
            Integer userId = list.get(i).getUserId();
            User user =  productService.getUserById(userId);
            list.get(i).setUser(user);
        }

        PageInfo page = new PageInfo(list, 4);

//            session.setAttribute("list",list);
//
//            session.setAttribute("page",page);

        return list;
    }

    @ResponseBody
    @RequestMapping("/getAllComment01")
    public Msg getAllComment01(@RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo , HttpSession session){

        Product product = (Product) session.getAttribute("product");

        System.out.println("product = " + product);

        Integer id = product.getId();


        PageHelper.startPage(pageNo,6);

        List<Comment>  list = productService.getAllCommentById(id);

        list.forEach(System.out::println);


        for (int i = 0; i < list.size(); i++) {
            Integer userId = list.get(i).getUserId();
            User user =  productService.getUserById(userId);
            list.get(i).setUser(user);
        }

        PageInfo page = new PageInfo(list, 4);


        return Msg.success().add("page",page);
    }

}
